#!/bin/bash
# $Id:$
# Project: PDP-8 simulator in Bash.
# Memory implementation.
# Copyright (c) 2010 Radek Hnilica

# Realizujeme jako jednorozměnrné pole.  Pole neinicializujeme.  Při
# čtení neinicializované slova bereme jako 0000.

declare -a memory		# Pole

# Manipulace s pamětí

# Usage: value=$(memory_read ADDR)
memory_read() {
    local -ir addr=${1:-0}
    
    # Check if address is in range.
    if (( 0 <= $addr && $addr < 4096 )); then
	local -ir data=${memory[$addr]:-0}
	echo $data
    else
	# Incorrect address.
	echo "ERROR Address $addr not in range <0,4095>." >&2
	exit $FAIL
    fi
}

# Usage: memory_write DATA ADDR
memory_write() {
    local -ir addr=$2 data=$1

    # Check both address and data.
    if ! (( 0 <= $addr && $addr < 4096 )); then
	echo "ERROR: Address $addr not in range <0,4095>." >&2
	exit $FAIL
    fi
    if ! (( 0 <= $data && $data < 4096 )); then
	echo "ERROR: Data  $data not in range <0,4095>." >&2
	exit $FAIL
    fi
    memory[$addr]=$data
}
